package com.beemans.common.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import com.beemans.common.app.CommonConfig
import com.beemans.common.utils.umeng.UMPlatform
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.commonsdk.statistics.common.DeviceConfig
import com.umeng.socialize.PlatformConfig
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import org.json.JSONObject

/**
 * @author tiamosu
 * @date 2021/3/15
 */
object UMConfig {
    private var isInit = false

    /**
     * 初始化友盟相关SDK
     */
    fun init(
        appKey: String,
        channel: String,
        pushSecret: String? = null,
        logEnabled: Boolean = false
    ) {
        isInit = true
        //设置组件化的Log开关
        UMConfigure.setLogEnabled(logEnabled)
        UMConfigure.init(Utils.getApp(), appKey, channel, UMConfigure.DEVICE_TYPE_PHONE, pushSecret)

        // 选用AUTO页面采集模式（Activity 中无需 onResume/onPause埋点）
        // 非Activity页面，需添加 onPageStart(name)/onPageEnd(name)
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
    }

    /**
     * 友盟分享初始化
     */
    fun initShare(
        platform: UMPlatform = UMPlatform.WECHAT,
        appId: String,
        appSecret: String,
        provider: String = "${CommonConfig.packageName}.utilcode.fileprovider"
    ) {
        if (!checkConfig()) return
        when (platform) {
            UMPlatform.WECHAT, UMPlatform.CIRCLE -> {
                PlatformConfig.setWeixin(appId, appSecret)
                PlatformConfig.setWXFileProvider(provider)
            }
            UMPlatform.QQ, UMPlatform.QZONE -> {
            }
            UMPlatform.ALIPAY -> {
            }
        }
    }

    /**
     * 友盟页面路径统计，在Fragment页面可见时调用
     */
    fun onPageFragmentStart(fragmentTag: String) {
        if (isInit) {
            MobclickAgent.onPageStart(fragmentTag)
        }
    }

    /**
     * 友盟页面路径统计，在Fragment页面不可见时调用
     */
    fun onPageFragmentEnd(fragmentTag: String) {
        if (isInit) {
            MobclickAgent.onPageEnd(fragmentTag)
        }
    }

    /**
     * 友盟分享所需，在MainActivity调用 [androidx.appcompat.app.AppCompatActivity.onSaveInstanceState]
     */
    fun onActivitySaveInstanceState(context: Context, outState: Bundle) {
        if (isInit) {
            UMShareAPI.get(context).onSaveInstanceState(outState)
        }
    }

    /**
     * 友盟分享所需，在MainActivity调用 [androidx.appcompat.app.AppCompatActivity.onActivityResult]
     */
    fun onActivityResult(context: Context, requestCode: Int, resultCode: Int, data: Intent?) {
        if (isInit) {
            UMShareAPI.get(context).onActivityResult(requestCode, resultCode, data)
        }
    }

    /**
     * 友盟分享所需，在MainActivity调用 [androidx.appcompat.app.AppCompatActivity.onDestroy]
     */
    fun onActivityRelease(context: Context) {
        if (isInit) {
            UMShareAPI.get(context).release()
        }
    }

    /**
     * 通过[platform]判断是否安装对应的应用，例如微信
     */
    fun isAppInstalled(platform: UMPlatform = UMPlatform.WECHAT): Boolean {
        return try {
            AppUtils.isAppInstalled(platform.packageName)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 通过[platform]判断是否已经授权，例如微信
     */
    fun isAuthorize(activity: Activity, platform: UMPlatform = UMPlatform.WECHAT): Boolean {
        if (!isInit) return false
        return UMShareAPI.get(activity).isAuthorize(activity, platform.thirdParty)
    }

    /**
     * @param isAuthByEveryTime 是否每次都进行手动授权，调起应用授权提示
     *
     * 通过shareMedia对应的应用进行授权，例如微信授权登录
     */
    fun doOauthVerify(
        activity: Activity,
        platform: UMPlatform = UMPlatform.WECHAT,
        isAuthByEveryTime: Boolean = false,
        onAuthCallback: AuthCallback.() -> Unit = {}
    ) {
        if (!checkConfig()) return
        var callback: AuthCallback? = AuthCallback().apply(onAuthCallback)
        //SDK默认设置为在Token有效期内登录不进行二次授权，如果有需要每次登录都弹出授权页面，需要设置
        if (isAuthByEveryTime) {
            // 删除旧的第三方登录授权
            UMShareAPI.get(activity).deleteOauth(activity, platform.thirdParty, null)
            // 要先等上面的代码执行完毕之后
            Thread.sleep(200)

            val config = UMShareConfig()
            config.isNeedAuthOnGetUserInfo(true)
            UMShareAPI.get(activity).setShareConfig(config)
        }
        UMShareAPI.get(activity)
            .getPlatformInfo(activity, platform.thirdParty, object : UMAuthListener {
                override fun onStart(shareMedia: SHARE_MEDIA?) {
                    callback?.onStart?.invoke(shareMedia)
                }

                override fun onComplete(
                    shareMedia: SHARE_MEDIA?,
                    i: Int,
                    map: MutableMap<String, String>?
                ) {
                    callback?.onComplete?.invoke(shareMedia, i, map)
                    callback = null
                }

                override fun onError(shareMedia: SHARE_MEDIA?, i: Int, throwable: Throwable?) {
                    callback?.onError?.invoke(shareMedia, i, throwable)
                    callback = null
                }

                override fun onCancel(shareMedia: SHARE_MEDIA?, i: Int) {
                    callback?.onCancel?.invoke(shareMedia, i)
                    callback = null
                }
            })
    }

    /**
     * 获取应用 oaid
     */
    fun getUmOaid(block: (oaid: String) -> Unit) {
        if (CommonCacheUtils.umOaid.isNotBlank()) {
            block.invoke(CommonCacheUtils.umOaid)
            return
        }
        kotlin.runCatching {
            UMConfigure.getOaid(Utils.getApp()) { oaid ->
                CommonCacheUtils.umOaid = oaid ?: ""
                block.invoke(oaid ?: "")
            }
        }.onFailure {
            block.invoke("")
        }
    }

    /**
     * 获取友盟实时日志所需，添加测试设备识别信息
     */
    fun getTestDeviceInfo(): String {
        val deviceInfo = arrayOfNulls<String>(2)
        try {
            deviceInfo[0] = DeviceConfig.getDeviceIdForGeneral(Utils.getApp())
            deviceInfo[1] = DeviceConfig.getMac(Utils.getApp())
        } catch (e: Exception) {
        }
        return JSONObject().apply {
            put("device_id", deviceInfo[0])
            put("mac", deviceInfo[1])
        }.toString()
    }

    private fun checkConfig(): Boolean {
        if (!isInit) {
            LogUtils.eTag("UMConfig", "Config is not init，u should call init first!")
            return false
        }
        return true
    }

    class AuthCallback {
        internal var onStart: ((shareMedia: SHARE_MEDIA?) -> Unit)? = null
        internal var onComplete: ((shareMedia: SHARE_MEDIA?, i: Int, map: MutableMap<String, String>?) -> Unit)? =
            null
        internal var onError: ((shareMedia: SHARE_MEDIA?, i: Int, throwable: Throwable?) -> Unit)? =
            null
        internal var onCancel: ((shareMedia: SHARE_MEDIA?, i: Int) -> Unit)? = null

        fun onStart(onStart: (shareMedia: SHARE_MEDIA?) -> Unit) {
            this.onStart = onStart
        }

        fun onComplete(onComplete: (shareMedia: SHARE_MEDIA?, i: Int, map: MutableMap<String, String>?) -> Unit) {
            this.onComplete = onComplete
        }

        fun onError(onError: (shareMedia: SHARE_MEDIA?, i: Int, throwable: Throwable?) -> Unit) {
            this.onError = onError
        }

        fun onCancel(onCancel: (shareMedia: SHARE_MEDIA?, i: Int) -> Unit) {
            this.onCancel = onCancel
        }
    }
}